package com.myproject.thread.volatiles;

public class VolatileTestAgain implements Runnable{

    private volatile ObjectA objectA;

    public ObjectA getObjectA() {
        return objectA;
    }

    public void setObjectA(ObjectA objectA) {
        this.objectA = objectA;
    }

    public VolatileTestAgain(ObjectA objectA) {
        this.objectA = objectA;
    }

    @Override
    public void run() {
        long i = 0;
        /*boolean flag = objectA.getSub().isFlag();
        while (!flag) {
            i++;
        }*/
        /*ObjectASub objectASub = objectA.getSub();
        while (!objectASub.isFlag()) {
            i++;
        }*/
        while (!objectA.getSub().isFlag()) {
            i++;
        }
        System.out.println(Thread.currentThread().getName()+": stop My Thread " + i);
    }

    public static void main(String[] args) throws InterruptedException {

        ObjectASub sub = new ObjectASub();
        ObjectA objectA = new ObjectA(sub);
        VolatileTestAgain test = new VolatileTestAgain(objectA);

        Thread thread = new Thread(test);
        thread.start();

        Thread.sleep(1000);
        //objectA.getSub().setFlag(true);
        sub.setFlag(true);
        Thread.sleep(1000);
        System.out.println(Thread.currentThread().getName()+": flag is " + test.getObjectA().getSub().isFlag());


        //ObjectA objectA = new ObjectA(new ObjectASub());
        /*ObjectASub objectASub = objectA.getSub();
        System.out.println(objectASub.isFlag());
        objectA.getSub().setFlag(true);
        System.out.println(objectASub.isFlag());*/
        /*boolean flag = objectA.getSub().isFlag();
        System.out.println(flag);
        objectA.getSub().setFlag(true);
        System.out.println(flag);*/

    }

    static class ObjectA {
        private ObjectASub sub;

        public ObjectASub getSub() {
            return sub;
        }

        public void setSub(ObjectASub sub) {
            this.sub = sub;
        }

        public ObjectA(ObjectASub sub) {
            this.sub = sub;
        }
    }

    static class ObjectASub{
        private boolean flag;

        public boolean isFlag() {
            return flag;
        }

        public void setFlag(boolean flag) {
            this.flag = flag;
        }
    }
}
